<template>
  <div class="app-container">
    <Ht-search-form
      :dictMap="dictMap"
      :searchExtend="extendSearch"
      :queryParams="queryParams"
      :outputQueryParams="queryParams"
      :formOptions="formOptions"
      :advOptions="[]"
      permission="user:roleInfo:view"
    ></Ht-search-form>

    <!-- 表格数据 -->
    <ht-table
      ref="dataTable"
      :multi-select="true"
      :dictMap="dictMap"
      :queryParams="queryParams"
      :tableBindColumns="tableBindColumns"
      :extendColumns="extendColumns"
      :opButtonList="opButtonList"
      :reqConfig="regConfig"
      :uploadServiceName="'authorityFileService'"
    >
      <template v-slot:operate>
        <el-table-column :label="$t('common.operate')" align="center" width="130" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['user:roleInfo:edit']">
              {{ $t("common.edit") }}
            </el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)" v-hasPermi="['user:roleInfo:remove']">
              {{ $t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </template>
    </ht-table>

    <!-- 添加或修改弹出框 -->
    <el-dialog
      :title="title"
      center
      :visible.sync="open"
      width="600px"
      append-to-body
      @close="close()"
      :close-on-click-modal="false"
    >
      <el-form ref="addForm" :model="addForm" :rules="rules" label-width="110px">
        <el-form-item :label="$t('authority.roleInfo.form.tenantSelection')" prop="tenantCode">
          <el-select
            class="common-select"
            v-model="addForm.tenantCode"
            :placeholder="$t('authority.roleInfo.rules.tenantPLH')"
            :disabled="tenantCodeIsAble || !mutiTeanant"
            @change="refreshTreeData"
          >
            <el-option :label="$t('authority.roleInfo.rules.tenantPLH')" value=""></el-option>
            <el-option
              v-for="item in tenantOptions"
              :key="item.tenantCode"
              :label="item.tenantName"
              :value="item.tenantCode"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('authority.roleInfo.form.roleName')" prop="roleName">
          <el-input
            :disabled="isAble"
            v-model="addForm.roleName"
            :placeholder="$t('authority.roleInfo.rules.roleNamePLH')"
          />
        </el-form-item>
        <el-form-item :label="$t('authority.roleInfo.form.roleKey')" prop="roleKey">
          <el-input
            :disabled="isAble"
            v-model="addForm.roleKey"
            :placeholder="$t('authority.roleInfo.rules.roleKeyPLH')"
          />
        </el-form-item>
        <el-form-item :label="$t('authority.roleInfo.form.state')" prop="status">
          <el-switch v-model="addForm.status" active-value="1" :disabled="isAble" inactive-value="2"></el-switch>
        </el-form-item>
        <el-form-item :label="$t('authority.roleInfo.form.postSort')" prop="roleSort">
          <el-input
            v-model="addForm.roleSort"
            :placeholder="$t('authority.roleInfo.rules.postSortPLH')"
            oninput="value=value.replace(/[^0-9]/g,'')"
            :disabled="isAble"
            maxlength="5"
          />
        </el-form-item>
        <el-form-item :label="$t('authority.roleInfo.form.remark')" prop="remark">
          <el-input
            v-model="addForm.remark"
            type="textarea"
            :disabled="isAble"
            :placeholder="$t('authority.roleInfo.rules.remarkPLH')"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('authority.roleInfo.form.menuPermission')" prop="menuIds">
          <div class="tree-container">
            <el-tree
              ref="tree"
              :data="treeData"
              :props="defaultProps"
              node-key="id"
              :disabled="isAble"
              show-checkbox
              @check-change="handleCheckChange"
            ></el-tree>
          </div>
        </el-form-item>
        <ht-extend-form
          ref="htExtendForm"
          v-if="extendColumns"
          :extendParams="extendColumns"
          :expandValueInfoMap="addForm.expandValueInfoMap"
          :dictReqFun="getDictReq"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t("common.confirm") }}</el-button>
        <el-button @click="cancel">{{ $t("common.cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { property } from "@/api/authority_app/base";
import {
  apiUrlConfig,
  updateRoleInfo,
  delRoleInfo,
  addRoleInfo,
  allMenuTreeNew,
  getMyTenants,
  listRoleMenuList,
  checkRoleName,
  checkRoleUpdatePermission,
  checkRoleKey,
} from "@/api/authority_app/role/roleInfo";
import { listPageMixin } from "@/libs/listPageMixin";
import { mapGetters } from "vuex";

export default {
  name: "RoleInfo",
  components: {},
  mixins: [listPageMixin],
  data() {
    var checkRoleNameUnique = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("authority.roleInfo.rules.roleNameNoEmpty")));
      } else {
        let formId = this.addForm.id == undefined ? "" : this.addForm.id;
        checkRoleName(formId, this.addForm.roleName).then((response) => {
          var result = response.result;
          if (!result) {
            callback(new Error(this.$t("authority.roleInfo.rules.roleNameExists")));
          } else {
            callback();
          }
        });
      }
    };
    var checkRoleKeyUnique = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("authority.roleInfo.rules.roleKeyNoEmpty")));
      } else {
        let formId = this.addForm.id == undefined ? "" : this.addForm.id;
        checkRoleKey(formId, this.addForm.roleKey).then((response) => {
          var result = response.result;
          if (!result) {
            callback(new Error(this.$t("authority.roleInfo.rules.roleKeyExists")));
          } else {
            callback();
          }
        });
      }
    };
    var checkNum = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("authority.roleInfo.rules.sortNoEmpty")));
      }
      if (!Number(value)) {
        callback(new Error(this.$t("authority.roleInfo.rules.numLimit")));
      }
      if (value.length > 5) {
        callback(new Error(this.$t("validate.lengthTip", { min: 1, max: 5 })));
      }
      callback();
    };
    return {
      mutiTeanant: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //菜单权限
      treeData: [],
      //级联关系
      defaultProps: {
        label: "name",
        children: "children",
      },
      tenantOptions: [],
      // 表单参数
      addForm: {
        roleName: "",
        roleKey: "",
        status: "1",
        remark: "",
        roleSort: "",
        tenantCode: "",
        menuIds: [],
        expandValueInfoMap: {},
      },
      extendParentKey: "3",
      opButtonList: () => {
        return [
          {
            label: this.$t("common.add"),
            type: "primary",
            icon: "el-icon-plus",
            permission: "user:roleInfo:add",
            actionType: "add",
            clickFun: () => {
              this.handleAdd();
            },
          },
          {
            label: this.$t("common.delete"),
            type: "danger",
            icon: "el-icon-plus",
            permission: "user:roleInfo:add",
            actionType: "del",
          },
        ];
      },
      formOptions: [],
      // 查询参数
      queryParams: {
        current: 1,
        limit: 10,
        roleName: "",
        roleKey: "",
        status: "",
      },
      regConfig: apiUrlConfig,

      isAble: false,
      tenantCodeIsAble: false,
      // 列信息
      tableBindColumns: [
        {
          label: this.$t("authority.roleInfo.form.id"),
          prop: "id",
          visible: false,
        },
        {
          label: this.$t("authority.roleInfo.form.tenantCode"),
          prop: "tenantCode",
        },
        {
          label: this.$t("authority.roleInfo.form.roleName"),
          prop: "roleName",
        },
        { label: this.$t("authority.roleInfo.form.roleKey"), prop: "roleKey" },
        {
          label: this.$t("authority.roleInfo.form.postSort"),
          prop: "roleSort",
        },
        {
          label: this.$t("authority.roleInfo.form.state"),
          prop: "status",
          visible: true,
          dictCode: "sys_normal_disable",
        },
        { label: this.$t("authority.roleInfo.form.remark"), prop: "remark" },
      ],
      // 表单校验
      rules: {
        roleName: [
          { required: true, trigger: "blur", validator: checkRoleNameUnique },
          {
            min: 1,
            max: 32,
            message: this.$t("validate.lengthTip", { min: 1, max: 32 }),
            trigger: "blur",
          },
        ],
        roleKey: [
          { required: true, trigger: "blur", validator: checkRoleKeyUnique },
          {
            min: 1,
            max: 32,
            message: this.$t("validate.lengthTip", { min: 1, max: 32 }),
            trigger: "blur",
          },
        ],
        roleSort: [{ required: true, validator: checkNum, trigger: "blur" }],
        remark: [
          {
            max: 500,
            message: this.$t("authority.roleInfo.rules.lengthLimit"),
            trigger: "blur",
          },
        ],
      },
      searchExtendColumns: [],
      showExtendSearch: false, // 是否展示高级搜索
      extendParamsDict: {}, // 扩展字段的字典数据
    };
  },
  mounted() {
    property().then((res) => {
      this.mutiTeanant = res.result.multipleCorporate;
    });
    const formOptions = [
      {
        type: "input",
        prop: "roleName",
        defaultAttr: {
          size: "small",
          label: this.$t("authority.roleInfo.form.roleName"),
          placeholder: this.$t("authority.roleInfo.rules.roleNamePLH"),
        },
      },
      {
        type: "input",
        prop: "roleKey",
        defaultAttr: {
          size: "small",
          label: this.$t("authority.roleInfo.form.roleKey"),
          placeholder: this.$t("authority.roleInfo.rules.roleKeyPLH"),
        },
      },
      {
        type: "dict",
        dict: "sys_normal_disable",
        prop: "status",
        defaultAttr: {
          size: "small",
          label: this.$t("authority.roleInfo.form.roleState"),
          placeholder: this.$t("authority.roleInfo.rules.roleStatePLH"),
        },
      },
    ];
    this.formOptions = formOptions;
  },
  methods: {
    getDictReq(dictCode) {
      return this.getDicts(dictCode);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.$set(this, "addForm", {
        roleName: "",
        roleKey: "",
        status: "1",
        remark: "",
        roleSort: "",
        menuIds: [],
        expandValueInfoMap: {},
      });
      // this.resetForm("addForm");
      this.$refs.htExtendForm.clearInput();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    refreshTreeData(tenantCode) {
      this.allMenuTreeNew(tenantCode);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm("addForm");
      this.$set(this, "addForm", {
        roleName: "",
        roleKey: "",
        status: "1",
        remark: "",
        roleSort: "",
        tenantCode: "",
        menuIds: [],
        expandValueInfoMap: {},
      });
      // this.getMyTenants();
      getMyTenants().then((response) => {
        this.tenantOptions = response.result;
        if (this.tenantOptions.length == 1) {
          this.addForm.tenantCode = this.tenantOptions[0].tenantCode;
          this.tenantCodeIsAble = true;
          this.allMenuTreeNew(this.tenantOptions[0].tenantCode);
        } else {
          this.allMenuTreeNew("");
        }
      });
      this.open = true;
      this.title = this.$t("authority.roleInfo.form.addRole");
      this.checkedReset();
      this.$nextTick((res) => {
        this.$refs.htExtendForm.genData();
      });
    },
    /** 修改按钮操作 */
    handleUpdate: function (row) {
      this.resetForm("addForm");
      this.checkedReset();
      this.open = true;
      this.title = this.$t("authority.roleInfo.form.updateRole");
      this.addForm.id = row.id;
      this.addForm.roleName = row.roleName;
      this.addForm.roleKey = row.roleKey;
      this.addForm.status = row.status + "";
      this.addForm.roleSort = row.roleSort;
      this.addForm.remark = row.remark || "";

      this.addForm.expandValueInfoMap = row.expandValueInfoMap || {};

      checkRoleUpdatePermission(row.tenantCode).then((response) => {
        this.isAble = !response.result;
        this.tenantCodeIsAble = !response.result;
      });

      allMenuTreeNew(row.tenantCode).then((response) => {
        this.treeData = response.result;

        this.queryRoleMenuList();
      });

      // this.getMyTenants();
      getMyTenants().then((response) => {
        this.tenantOptions = response.result;
      });
      this.addForm.tenantCode = row.tenantCode + "";

      this.$nextTick((res) => {
        this.$refs.htExtendForm.genData();
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          this.addForm.expandValueInfoMap = this.$refs.htExtendForm.getExtendParamsValue();
          if (this.addForm.menuIds.length < 1) {
            this.addForm.menuIds.push("");
          }
          if (this.addForm.id) {
            updateRoleInfo(this.addForm).then((response) => {
              this.msgSuccess(this.$t("authority.roleInfo.rules.updateTip"));
              this.open = false;
              this.doQuery();
              this.reset();
            });
          } else {
            addRoleInfo(this.addForm).then((response) => {
              this.msgSuccess(this.$t("common.addSuccess"));
              this.open = false;
              this.doQuery();
              this.reset();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$confirm(this.$t("authority.roleInfo.rules.deleteTips"), this.$t("authority.roleInfo.form.warning"), {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(function () {
          return delRoleInfo(id);
        })
        .then(() => {
          this.doQuery();
          this.msgSuccess("操作成功，待审核");
        })
        .catch((action) => {});
    },

    //查询角色菜单权限
    allMenuTreeNew(tenantCode) {
      allMenuTreeNew(tenantCode).then((response) => {
        this.treeData = response.result;
      });
    },

    getMyTenants() {
      getMyTenants().then((response) => {
        this.tenantOptions = response.result;
        if (this.tenantOptions.length == 1) {
          this.addForm.tenantCode = this.tenantOptions[0].tenantCode;
          this.tenantCodeIsAble = true;
        }
      });
    },

    //查询角色菜单权限
    queryRoleMenuList() {
      listRoleMenuList({ roleId: this.addForm.id }).then((response) => {
        response.result.forEach((id) => {
          this.$refs.tree.setChecked(id, true);
        });
      });
    },

    //选中变更
    //属性组件选择后的回调
    handleCheckChange() {
      let temp = this.$refs.tree.getCheckedKeys();
      var ids = temp.concat(this.$refs.tree.getHalfCheckedKeys());
      this.addForm.menuIds = ids;
    },

    //选中重置
    checkedReset() {
      if (this.$refs.tree) {
        var ids = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());
        if (ids.length > 0) {
          this.$refs.tree.setCheckedKeys([]);
        }
      }
    },
    changeShowExtendSearch(state) {
      this.$refs.htExtendSearch.changeShowState(state);
    },
    // 取消按钮
    close() {
      this.open = false;
      this.$nextTick((res) => {
        this.$refs.htExtendForm.clearInput();
      });
    },
  },
};
</script>
<style>
.tree-container {
  max-height: 350px;
  overflow: auto;
}
</style>
